
//Justin Adams

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.File;
import java.util.ArrayList;
import tttCore.*;

@SuppressWarnings("serial")
public class TTTPvPServlet  extends HttpServlet{


	protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		response.setContentType("text/xml");
		PrintWriter out = response.getWriter();
		String path = request.getPathInfo();
		BufferedReader rd = request.getReader();
		StringBuilder sb = new StringBuilder();
		String responseString = "";


		path = path.substring(1);
		// make the pvp manager
		PvPManager PMan = new PvPManager(path);

		if(path.matches("resetFile")){
			// if a request is sent to reset the the file, do so
			ArrayList<String> lines = PMan.getFileLines();
			responseString = lines.get(0); // return the game board to the client
			// and the game status to the response string
			responseString = responseString + ";" + PMan.getStatus();
			PMan.resetFile();	
		}else{

			if(path.matches("checkx")){ // if the user is checking to see if they can be x. this is always the first thing the client asks
				ArrayList<String> lines = PMan.getFileLines();
				responseString = lines.get(0);
				if(responseString.matches("NNNNNNNNN")){ // if x is taken you are the second person to connect you are O
					responseString = "false";
				}
				else if(responseString.matches("xIsNotTaken")){ // if x is not taken you are the second person to connect, you are X
					responseString = "true";
					PMan.writeToFile("NNNNNNNNN"); // set the file to indicate that x is taken
				}
			}
			else{ // if the user is not checking for x, they are playing a game
				boolean RWboard = true;
				if(path.matches("listening")){
					RWboard= false;
				}
				PMan.performPlayerMove(RWboard);
				ArrayList<String> lines = PMan.getFileLines();
				responseString = lines.get(0); // return the game board to the client
				// and the game status to the response string
				responseString = responseString + ";" + PMan.getStatus();
			}

		}

		int ch;
		while ( (ch=rd.read()) != -1 ) {
			sb.append( (char)ch);
		}
		out.println( "<?xml version='1.0'?>" );
		// send response tp client
		out.println("<info>" + responseString + "</info>");

	}
}
